/**
 * @author yhim
 */

function init() {
    var s = document.getElementById("ts-file");

    // s.addEventListener("change", function() {tsFileLoad(this.files);},
    // false);
    s.addEventListener("change", tsFileChange, false);
    // alert('init');
}

var file;
var reader;

var nextReadPos = 0;
var readSize = 10240;

var reading = document.getElementById("ts-file-reading");
var bitrates = document.getElementById("ts-file-bitrates");
var ccError = document.getElementById("ts-file-cc-errors");

/*
 *  initialize elementary on panel 'General Information'
 */
function initPanelGeneralInformation() {
    document.getElementById("ts-file-name").textContent = file.name;
    document.getElementById("ts-file-size").textContent = file.size + " bytes";
    document.getElementById("ts-file-type").textContent = file.type;

    bitrates.textContent = "";
    ccError.textContent = "";
    reading.style.width = '0%';
    reading.textContent = '0%';
}

/*
 *  initialize elementary on panel 'Packet Statistics'
 */
function initPacketStatistics() {
    $('.tb-statistics-data').remove();
}

/*
 *  initialize elementary on panel 'Active PIDs'
 */
function initActivePids() {
    $('#id-active-pids').remove();
}

/*
 *  initialize elementary on panel 'Packet Analysis'
 */
function initPacketAnalysis() {
    var ta_packet_desc = document.getElementById("ta-packet-desc");
    var ta_packet_raw = document.getElementById("ta-packet-raw");
    ta_packet_desc.textContent = "";
    ta_packet_raw.textContent = "";
}

function initPanel() {
    initPanelGeneralInformation ();
    initPacketStatistics ();
    initActivePids ();
    initPacketAnalysis ();
}

function tsFileLoadProgress(evt) {
	var percentLoaded = Math.round((nextReadPos / file.size) * 100);
	// Increase the progress bar length.
	if (percentLoaded < 100) {
		reading.style.width = percentLoaded + '%';
		reading.textContent = percentLoaded + '%';
	}

/*	// evt is an progress Event.
	if (evt.lengthComputable) {
		var percentLoaded = Math.round((evt.loaded / evt.total) * 100);
		// Increase the progress bar length.
		if (percentLoaded < 100) {
			reading.style.width = percentLoaded + '%';
			reading.textContent = percentLoaded + '%';
		}
	}*/
}

function tsFileLoad(evt) {
    if (evt.target.readyState == FileReader.DONE) {
        // parse TS packet.
        
        // check to load end.
     	if (nextReadPos >= file.size) {
            document.getElementById("ta-packet-raw").textContent = evt.target.result;

            reading.style.width = '100%';
            reading.textContent = '100%';
    	}
    	else {
            tsFileReadNext ();
    	}
    }
}

function tsFileError(evt) {
    switch (evt.target.error.code) {
        case evt.target.error.NOT_FOUND_ERR:
            //alert('File Not Found!');
            break;
        case evt.target.error.NOT_READABLE_ERR:
            alert('File is not readable');
            break;
        case evt.target.error.ABORT_ERR:
            break;
        // noop
        default:
            alert('An error occurred reading this file.');
    }
}

function tsFileChange(evt) {
	//var fileInput = document.getElementById("ts-file");
    //var file = fileInput.files[0];
    file = evt.target.files[0];

    if (file.type.match('video.*')) {
        reader = new FileReader();
    
        reader.onprogress = tsFileLoadProgress;
        reader.onload = tsFileLoad;
        reader.onerror = tsFileError;

        initPanel ();

    	nextReadPos = 0;
        if ((file.size % 188) == 0) {
        	readSize *= 188;
        }
        else {
        	readSize *= 204;
        }

        tsFileReadNext ();
    }
    else {
        alert("Please select one of Video TS files!");
    }
}

function tsFileReadNext () {
    var readEndPos;

    if ((nextReadPos + readSize) >= file.size) {
    	readSize = file.size - nextReadPos;
    }
    readEndPos = nextReadPos + readSize;
    tsFileReadBlock (nextReadPos, readEndPos);	

	nextReadPos += readSize;
}

function tsFileReadBlock (startPos, stopPos) {
    var blobN;

    blobN = file.slice (startPos, stopPos);	
    reader.readAsBinaryString (blobN);
}

/*
var ds = new DataStream(buffer);
// with DataStream.readStruct
ds.readStruct([
  'objs', ['[]', [ // objs: array of tag,length,data structs
    'tag', 'uint16',
    'length', 'uint16',
    'data', ['[]', 'uint8', function(s,ds){ return s.length - 2; }], // get length with a function
  '*'] // read in as many struct as there are
]);
*/
